﻿using System;
using System.Data.Common;
using System.Linq;

namespace FastData.DataProvider
{
    public class SqlCeProviderFactory : DataProviderFactory
    {
        public override string ProviderName
        {
            get { return "System.Data.SqlServerCe.4.0"; }
        }

        internal override string CreateSelectText(QueryBase query, ExecuteType type)
        {
            string from = GetDbObjectName(query.TableName);
            foreach (var join in query.Joins)
            {
                from += " " + join.Type.GetName() + " JOIN " + GetDbObjectName(join.TableName) + " ON " + join.Where;
            }

            if (query.SkipCount == 0)
            {
                return "SELECT " + (query.IsDistinct ? "DISTINCT " : "") + (query.TakeCount > 0 ? "TOP " + query.TakeCount + " " : "") + query.FieldNames + " FROM " + from + " " + query.WhereText + " " + query.OrderByText;
            }
            return "SELECT " + (query.IsDistinct ? "DISTINCT " : "") + query.FieldNames + " FROM " + from + " " + query.WhereText + " " + query.OrderByText + " OFFSET " + query.SkipCount + " ROWS FETCH NEXT " + query.TakeCount + " ROWS ONLY";
        }

        public override string GetDbObjectName(string name)
        {
            name = name.Trim();
            if (name == "*" || name.IndexOf('(') > 0 || name.IndexOf(' ') > 0)
            {
                return name;
            }

            return string.Join(".", name.Split('.').Select(n => n[0] == '[' ? n : "[" + n + "]"));
        }

        public override string GetDbParameterName(string name)
        {
            return "@" + name;
        }

        public override SelectQuery GetViewTableUsage(DataAccess data, string viewName)
        {
            throw new NotSupportedException();
        }

        public override bool SupportBatchCommand
        {
            get { return false; }
        }

        public override bool SupportInsertedId
        {
            get { return false; }
        }

        internal override string LastIdentityText
        {
            get { return "SELECT @@IDENTITY"; }
        }
    }

}
